<?php

namespace App\Http\Controllers\Home;

use DB;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;
use App\Http\Controllers\Controller;
use App\Http\Controllers\QueryController;

use App\Http\Models\Member;

class UserController extends Controller {

    protected $query = null;

    public function __construct(){
        $this->query = new QueryController();
    }

    public function isLogin(){
        session_start();
        if($_SESSION['loginUser']){
            return true;
        }
        return false;
    }



    public function login(Request $request){
        $username = $request->input('username');
        $password = $request -> input('password');
        $member = Member::where('username',$username)->where("password",md5($password))->first();
        if($member){
            session_start();
            $_SESSION['loginUser'] = $member;
            return response()->json(['state'=>'ok','message'=>'登录成功']);
        }
        return response()->json(['state'=>'err','message'=>'登录失败']);
    }

    public function register(Request $request){
        $username = $request->input('username');
        $password = $request -> input('password');
        $repassword = $request -> input('repassword');
        if(!$password || ($repassword !== $password)){
            return response()->json(['state'=>'err',"message"=>"两次密码不一致"]);
        }
        $count = Member::where("username",$username)->count();
        if($count){
            return response()->json(['state'=>'err',"message"=>"该用户名已经存在了"]);
        }
        $res = Member::insert(["username"=>$username,"password"=>md5($password),"created_at"=>date("Y-m-d H:i:s",time()),"updated_at"=>date("Y-m-d H:i:s",time())]);
        if($res){
            return response()->json(['state'=>'ok','message'=>'注册成功']);
        }
        return response()->json(['state'=>'err','message'=>'注册失败']);
    }


}
